
package com.platform.modules.mall.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.platform.common.annotation.SysLog;
import com.platform.common.dataImport.ShopsImport;
import com.platform.common.utils.Constant;
import com.platform.common.utils.EasyPoiUtils;
import com.platform.common.utils.RestResponse;
import com.platform.common.utils.StringUtils;
import com.platform.modules.mall.entity.MallShopsEntity;
import com.platform.modules.mall.service.MallAssociTagService;
import com.platform.modules.mall.service.MallBrandService;
import com.platform.modules.mall.service.MallShopsService;
import com.platform.modules.sys.controller.AbstractController;
import com.platform.modules.sys.service.SysUserRoleService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 店铺Controller
 *
 * @author
 * @date 2019-07-03 13:51:29
 */
@RestController
@RequestMapping("mall/shops")
public class MallShopsController extends AbstractController {
    @Autowired
    private MallShopsService mallShopsService;
    @Autowired
    private SysUserRoleService sysUserRoleService;
    @Resource
    private MallBrandService brandService;
    @Resource
    private MallAssociTagService associTagService;
    private String key = "XIBBZ-I3IWD-Z7O4S-H5TYK-5X3PF-DDFL4";
    private String url = "https://apis.map.qq.com/ws/geocoder/v1/?address=%s&key=%s";

    /**
     * 查看所有列表
     *
     * @param params 查询参数
     * @return RestResponse
     */
    @RequestMapping("/queryAll")
    @RequiresPermissions("mall:shops:list")
    public RestResponse queryAll(@RequestParam Map<String, Object> params) {

        //获取用户所属的角色列表
//        List<String> roleIdList = sysUserRoleService.queryRoleIdList(this.getUserId());
//        if (roleIdList.contains(Constant.ORG_ADMIN)) {
//            params.put("orgNo", this.getOrgNo());
//        }
        //else if (!(this.getUserId().equals(Constant.SUPER_ADMIN) || roleIdList.contains(Constant.ADMIN))) {
//            params.put("userId", this.getUserId());
//        }
        List<MallShopsEntity> list = mallShopsService.queryAll(params);

        return RestResponse.success().put("list", list);
    }

    /**
     * 查看所有列表
     *
     * @param params 查询参数
     * @return RestResponse
     */
    @RequestMapping("/queryAllSimple")
    public RestResponse queryAllSimple(@RequestParam Map<String, Object> params) {

        String name = (String) params.get("name"),
                userId = null, orgNo = null,
                level = (String) params.get("level"),
                type = (String) params.get("type");
        //获取用户所属的角色列表
        List<String> roleIdList = sysUserRoleService.queryRoleIdList(this.getUserId());
        if (roleIdList.contains(Constant.ORG_ADMIN)) {
            orgNo = this.getOrgNo();
        } else if (!(this.getUserId().equals(Constant.SUPER_ADMIN) || roleIdList.contains(Constant.ADMIN))) {
            userId = this.getUserId();
        }
        List<MallShopsEntity> list = mallShopsService.list(new QueryWrapper<MallShopsEntity>()
                .select("ID", "NAME")
                .like(StringUtils.isNotBlank(name), "NAME", name)
                .eq(StringUtils.isNotBlank(userId), "USER_ID", userId)
                .eq(StringUtils.isNotBlank(orgNo), "ORG_NO", orgNo)
                .eq(StringUtils.isNotBlank(type), "TYPE", type)
                .eq(StringUtils.isNotBlank(level), "LEVEL", level));

        return RestResponse.success().put("list", list);
    }

    /**
     * 分页查询店铺
     *
     * @param params 查询参数
     * @return RestResponse
     */
    @GetMapping("/list")
    @RequiresPermissions("mall:shops:list")
    public RestResponse list(@RequestParam Map<String, Object> params) {
        IPage page = mallShopsService.queryPage(params);

        return RestResponse.success().put("page", page);
    }

    /**
     * 根据主键查询详情
     *
     * @param id 主键
     * @return RestResponse
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("mall:shops:info")
    public RestResponse info(@PathVariable("id") String id) {
        MallShopsEntity mallShops = mallShopsService.getShopByIdForApp(id);

        return RestResponse.success().put("shops", mallShops);
    }

    /**
     * 新增店铺
     *
     * @param mallShops mallShops
     * @return RestResponse
     */
    @SysLog("新增店铺")
    @RequestMapping("/save")
    @RequiresPermissions("mall:shops:save")
    public RestResponse save(@RequestBody MallShopsEntity mallShops) {
//        if (StringUtils.isNotBlank(mallShops.getUserId())) {
//            MallShopsEntity shopsEntity = mallShopsService.getOne(new LambdaQueryWrapper<MallShopsEntity>().select(MallShopsEntity::getId)
//                    .eq(MallShopsEntity::getUserId, mallShops.getUserId()));
//            if (shopsEntity != null || StringUtils.isNotBlank(shopsEntity.getId())) {
//                return RestResponse.error("店铺管理员已经管理其他店铺，请选择其他人员管理");
//            }
//        }

        mallShops.setCreateTime(new Date());
        mallShops.setCreateUserId(getUserId());
        mallShopsService.add(mallShops);


        return RestResponse.success();
    }


    /**
     * 导入文件批量新增
     *
     * @param file file
     * @return RestResponse
     */
    @SysLog("店铺导入")
    @RequestMapping("/uploadSave")
    @RequiresPermissions("mall:shops:uploadSave")
    public Object u0pload(@RequestParam(value = "file", required = false) MultipartFile file) throws Exception {
        EasyPoiUtils.importExcel(file,new ShopsImport(mallShopsService,brandService));
        /*if (null == file || file.isEmpty()) {
            throw new BusinessException("上传文件不能为空");
        }

        EasyPoiUtils.checkFile(file);
        // 上传文件
        Map<String, List<String[]>> map = EasyPoiUtils.readExcel(file.getOriginalFilename(), file.getInputStream());
        Iterator<Map.Entry<String, List<String[]>>> it = map.entrySet().iterator();
        List<String[]> list = new ArrayList();
        while (it.hasNext()) {
            Map.Entry<String, List<String[]>> entry = it.next();
            list = entry.getValue();
            break;
        }
        MallShopsEntity shopsEntity;
        Date date = new Date();
        List<MallShopsEntity> shopsEntities = new ArrayList(list.size());
        for (int i = 1, num = list.size(); i < num; i++) {
            try {
                if (StringUtils.isNotBlank(list.get(i)[1]) && StringUtils.isNotBlank(list.get(i)[0])) {
                    shopsEntity = new MallShopsEntity();
                    shopsEntity.setName(list.get(i)[0]);
                    shopsEntity.setShopDesc(list.get(i)[0]);
                    shopsEntity.setCreateUserId(this.getUserId());
                    shopsEntity.setCreateTime(date);
                    shopsEntity.setTelephone(list.get(i)[4]);
                    shopsEntity.setDetails(list.get(i)[5]);
                    if (list.get(i).length > 6) {
//                        shopsEntity.setLatitude(list.get(i)[6]);
//                        shopsEntity.setLongitude(list.get(i)[7]);
                    }
                    shopsEntity.setType(NumberUtils.toInt(list.get(i)[1]));
                    if (shopsEntity.getType() == 2) {
                        shopsEntity.setOrgNo(list.get(i)[3]);
                    }
                    shopsEntity.setLevel(NumberUtils.toInt(list.get(i)[2]));
                    if (shopsEntity.getLevel() == 2 && StringUtils.isNotBlank(list.get(i)[3])) {
                        shopsEntity.setParentId(list.get(i)[3]);
                    }
                    if (!"0".equals(shopsEntity.getDetails())) {
                        JSONObject js = JSONObject.parseObject(HttpUtils.sendGet(String.format(url, shopsEntity.getDetails(), key)));
                        if (ObjectUtils.equals(js.getString("status"), "0")) {
//                            shopsEntity.setLatitude(js.getJSONObject("result").getJSONObject("location").getString("lat"));
//                            shopsEntity.setLongitude(js.getJSONObject("result").getJSONObject("location").getString("lng"));
                        }
                    }

                    shopsEntities.add(shopsEntity);
                }
            } catch (Exception e) {
                logger.error("", e);
            }
        }

        if (shopsEntities.size() > 0) {
            mallShopsService.saveBatch(shopsEntities);
        }*/

        return RestResponse.success();
    }


    /**
     * 修改店铺
     *
     * @param mallShops mallShops
     * @return RestResponse
     */
    @SysLog("修改店铺")
    @RequestMapping("/update")
    @RequiresPermissions("mall:shops:update")
    public RestResponse update(@RequestBody MallShopsEntity mallShops) {
//        if (StringUtils.isNotBlank(mallShops.getUserId())) {
//            MallShopsEntity shopsEntity = mallShopsService.getOne(new LambdaQueryWrapper<MallShopsEntity>().select(MallShopsEntity::getId)
//                    .eq(MallShopsEntity::getUserId, mallShops.getUserId()));
//            if ((shopsEntity != null || StringUtils.isNotBlank(shopsEntity.getId())) && !ObjectUtils.equals(mallShops.getId(), shopsEntity.getId())) {
//                return RestResponse.error("店铺管理员已经管理其他店铺，请选择其他人员管理");
//            }
//        }

        mallShopsService.update(mallShops);

        return RestResponse.success();
    }

    /**
     * 修改店铺图片
     *
     * @param params 查询参数
     * @return RestResponse
     */
    @RequestMapping("/updateImage")
    @RequiresPermissions("mall:shops:save")
    public RestResponse updateImage(@RequestParam Map<String, Object> params) {
        mallShopsService.update(new UpdateWrapper<MallShopsEntity>().set("img_list", params.get("imgs")).eq("id", params.get("id")));
        return RestResponse.success();
    }

    /**
     * 根据主键删除店铺
     *
     * @param ids ids
     * @return RestResponse
     */
    @SysLog("删除店铺")
    @RequestMapping("/delete")
    @RequiresPermissions("mall:shops:delete")
    public RestResponse delete(@RequestBody String[] ids) {
        mallShopsService.deleteBatch(ids);
        for(String id : ids){
            associTagService.delateByAssoci(id,null);
        }
        return RestResponse.success();
    }

    /**
     * 分页查询我的店铺
     *
     * @param params 查询参数
     * @return RestResponse
     */
    @GetMapping("/myShop")
    @RequiresPermissions("mall:shops:myShop")
    public RestResponse myShop(@RequestParam Map<String, Object> params) {
        params.put("userId", getUserId());
        IPage page = mallShopsService.queryPage(params);

        return RestResponse.success().put("page", page);
    }

    /**
     * 查询我的所有店铺
     *
     * @param params 查询参数
     * @return RestResponse
     */
    @RequestMapping("/queryMyShop")
    @RequiresPermissions("mall:shops:myShop")
    public RestResponse queryMyShop(@RequestParam Map<String, Object> params) {
        params.put("userId", getUserId());
        List<MallShopsEntity> list = mallShopsService.queryAll(params);

        return RestResponse.success().put("list", list);
    }

    /**
     * 修改我的店铺
     *
     * @param mallShops mallShops
     * @return RestResponse
     */
    @SysLog("修改店铺")
    @RequestMapping("/myUpdate")
    @RequiresPermissions("mall:shops:myUpdate")
    public RestResponse myUpdate(@RequestBody MallShopsEntity mallShops) {

        mallShopsService.myUpdate(mallShops, getUserId());

        return RestResponse.success();
    }
}
